package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;


import com.alibaba.citrus.ots.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.bcorder.service.SalesPlanService;
import com.epoch.app.otsapplicationappsdk.tododetail.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.tododetail.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.tododetail.dto.SubmitRequest;
import com.epoch.app.otsapplicationappsdk.tododetail.service.TodoDetailService;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
public class TodoDetailV2ServiceImpl implements TodoDetailService {

    private static Log log = Log.getLogger(ChannelListPageV2ServiceImpl.class);

    @Autowired
    private SalesPlanService salesPlanService;

//    @Autowired
//    private BcOtsService bcOtsService;
    @Autowired
    private BcOrderService bcOtsService;

    @Override
    public Object render(RenderRequest renderRequest) {
        log.info("待办任务详情渲染页面请求参数 {} ", JSONObject.toJSONString(renderRequest));

        JSONObject result = new JSONObject();
        int limit = 10;
        if (renderRequest.getPageSize() != null && renderRequest.getPageSize() > 0) {
            limit = renderRequest.getPageSize();
        }
        if (renderRequest.getCurrentPage() == null) {
            renderRequest.setCurrentPage(1);
        }
        try {
            PageQueryPlanScItemListResponse listResponse = null;

            result.put("activeTab", renderRequest.getActiveTab());
            QuerySalePlanInfoRequest infoRequest = new QuerySalePlanInfoRequest();
            infoRequest.setId(renderRequest.getPlanId());
            QuerySalePlanInfoResponse infoResponse = salesPlanService.querySalePlanInfo(infoRequest);
            result.put("infoResponse", infoResponse.getResult());

            if (null != renderRequest.getType() && "2".equals(renderRequest.getType())) {
                List childOrgList = new ArrayList();
                listResponse = getChildOrgList(renderRequest.getBizId(), null, SalesStatBizTypeEnum.get(renderRequest.getBizType()).getOrganizationType(), renderRequest.getPlanId(), null);
                childOrgList = listResponse.getResult();
                result.put("listResponse", childOrgList);

                EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
                if (employeeGetCurrentLoginResponse != null) {
                    log.info("待办任务详情渲染页面 当前登录人API结果 {} ", JSONObject.toJSONString(employeeGetCurrentLoginResponse));
                }
                result.put("isSales", employeeGetCurrentLoginResponse.getIsSales());

                PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
                listRequest.setPlanId(renderRequest.getPlanId());
                listRequest.setBizType(SalesStatBizTypeEnum.get(renderRequest.getBizType()).getOrganizationType());
                listRequest.setBizId(renderRequest.getBizId());
                listRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());

                PageQueryPlanScItemListResponse response = salesPlanService.pageQueryPlanScItemList(listRequest);
                String reportOrderId = "";
                if (Objects.nonNull(response) && CollectionUtils.isNotEmpty(response.getResult())) {
                    List list = response.getResult();
                    reportOrderId = JSONObject.parseObject(JSON.toJSONString(list.get(0))).getString("reportOrderId");
                }

                SubTotalSalesPlanSCItemRequest itemRequest = new SubTotalSalesPlanSCItemRequest();
                itemRequest.setBizId(renderRequest.getBizId());
                itemRequest.setBizType(SalesStatBizTypeEnum.get(renderRequest.getBizType()).getOrganizationType());
                itemRequest.setPlanId(renderRequest.getPlanId());
                itemRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
                SubTotalSalesPlanSCItemResponse itemResponse = salesPlanService.subTotalSalesPlanSCItem(itemRequest);
                result.put("itemResponse", itemResponse.getResult());

                if (StringUtils.isNotBlank(reportOrderId)) {
                    QuerySalesPlanAuditRecordListRequest reportRequest = new QuerySalesPlanAuditRecordListRequest();
                    reportRequest.setAuditReportId(reportOrderId);
                    Result<List<SalesPlanAuditRecord>> recordList = salesPlanService.querySalesPlanAuditRecordList(reportRequest);
                    result.put("recordList", recordList.getResult());
                }
            } else {
                PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
                listRequest.setPlanId(renderRequest.getPlanId());
                listRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
                listRequest.setPage(renderRequest.getCurrentPage());
                listRequest.setSize(limit);
                listResponse = salesPlanService.pageQueryPlanScItemList(listRequest);
                result.put("listResponse", listResponse.getResult());

                SubTotalSalesPlanSCItemRequest itemRequest = new SubTotalSalesPlanSCItemRequest();
                itemRequest.setPlanId(renderRequest.getPlanId());
                itemRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
                SubTotalSalesPlanSCItemResponse itemResponse = salesPlanService.subTotalSalesPlanSCItem(itemRequest);
                result.put("itemResponse", itemResponse.getResult());
            }

            result.put("type", renderRequest.getType());

            int totalPage = listResponse.getTotal() / limit;
            if (listResponse.getTotal() % limit > 0) {
                totalPage++;
            }
            result.put("totalPage", totalPage);

            result.put("success", true);
            result.put("message", "");

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "页面跑丢了");
        }
        return result;
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        log.info("待办任务列表页面异步请求参数 {} ", JSONObject.toJSONString(asyncRequest));
        Object request = asyncRequest.getRequest();
        if (request == null) {
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(request));
            JSONObject fields = jsonObject.getJSONObject("fields");
            Integer currentPage = fields.getInteger("currentPage");
            Integer pageSize = fields.getInteger("pageSize");
            String planId = fields.getString("planId");
            String bizId = fields.getString("bizId");
            String bizType = fields.getString("bizType");
            result.put("activeTab", fields.getString("activeTab"));
            int limit = 10;
            if (pageSize != null && pageSize > 0) {
                limit = pageSize;
            }
            if (currentPage == null) {
                currentPage = 1;
            }

            PageQueryPlanScItemListResponse listResponse = null;
            QuerySalePlanInfoRequest infoRequest = new QuerySalePlanInfoRequest();
            infoRequest.setId(planId);
            QuerySalePlanInfoResponse infoResponse = salesPlanService.querySalePlanInfo(infoRequest);
            result.put("infoResponse", infoResponse.getResult());
            if (null != fields.getString("type") && "2".equals(fields.getString("type"))) {
                List childOrgList = new ArrayList();
                listResponse = getChildOrgList(bizId, null, SalesStatBizTypeEnum.get(Integer.parseInt(bizType)).getOrganizationType(), planId, null);
                childOrgList = listResponse.getResult();
                result.put("listResponse", childOrgList);

                EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
                if (employeeGetCurrentLoginResponse != null) {
                    log.info("待办任务详情异步页面 当前登录人API结果 {} ", JSONObject.toJSONString(employeeGetCurrentLoginResponse));
                }
                result.put("isSales", employeeGetCurrentLoginResponse.getIsSales());

                PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
                listRequest.setPlanId(planId);
                listRequest.setBizType(SalesStatBizTypeEnum.get(Integer.parseInt(bizType)).getOrganizationType());
                listRequest.setBizId(bizId);
                listRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());

                PageQueryPlanScItemListResponse response = salesPlanService.pageQueryPlanScItemList(listRequest);
                String reportOrderId = "";
                if (Objects.nonNull(response) && CollectionUtils.isNotEmpty(response.getResult())) {
                    List list = response.getResult();
                    reportOrderId = JSONObject.parseObject(JSON.toJSONString(list.get(0))).getString("reportOrderId");
                }

                SubTotalSalesPlanSCItemRequest itemRequest = new SubTotalSalesPlanSCItemRequest();
                itemRequest.setBizId(bizId);
                itemRequest.setBizType(SalesStatBizTypeEnum.get(Integer.parseInt(bizType)).getOrganizationType());
                itemRequest.setPlanId(planId);
                itemRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
                SubTotalSalesPlanSCItemResponse itemResponse = salesPlanService.subTotalSalesPlanSCItem(itemRequest);
                result.put("itemResponse", itemResponse.getResult());

                if (StringUtils.isNotBlank(reportOrderId)) {
                    QuerySalesPlanAuditRecordListRequest reportRequest = new QuerySalesPlanAuditRecordListRequest();
                    reportRequest.setAuditReportId(reportOrderId);
                    Result<List<SalesPlanAuditRecord>> recordList = salesPlanService.querySalesPlanAuditRecordList(reportRequest);
                    result.put("recordList", recordList.getResult());
                }
            } else {
                PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
                listRequest.setPlanId(fields.getString("planId"));
                listRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
                listRequest.setPage(currentPage);
                listRequest.setSize(limit);

                SubTotalSalesPlanSCItemRequest itemRequest = new SubTotalSalesPlanSCItemRequest();
                itemRequest.setPlanId(planId);
                itemRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
                SubTotalSalesPlanSCItemResponse itemResponse = salesPlanService.subTotalSalesPlanSCItem(itemRequest);
                result.put("itemResponse", itemResponse.getResult());

                try {
                    listResponse = salesPlanService.pageQueryPlanScItemList(listRequest);
                    result.put("listResponse", listResponse.getResult());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            result.put("pageSize", limit);
            result.put("currentPage", currentPage);
            result.put("total", listResponse.getTotal());
            int totalPage = listResponse.getTotal() / limit;
            if (listResponse.getTotal() % limit > 0) {
                totalPage++;
            }
            result.put("totalPage", totalPage);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "页面跑丢了");
        }
        return result;
    }

    @Override
    public Object submit(SubmitRequest submitRequest) {
        log.info("待办任务详情提交页面请求参数 {} ", JSONObject.toJSONString(submitRequest));

        Object request = submitRequest.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        JSONObject result = new JSONObject();

        JSONObject json = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(request));
            JSONObject fields = jsonObject.getJSONObject("fields");
            result.put("modelId", fields.getString("planId"));
            result.put("model", 1);
            result.put("action", fields.getString("action"));
            if (null != fields.getString("remake")) {
                result.put("comment", fields.getString("remake"));
            }

            List list = new ArrayList();
            Biz biz = new Biz();
            biz.setBizId(fields.getString("bizId"));
            biz.setBizType(fields.getInteger("bizType"));
            list.add(biz);

            result.put("dimensionDTOList", list);
            BatchSubmitTaskRequest batchSubmitTaskRequest = result.toJavaObject(BatchSubmitTaskRequest.class);
            BatchSubmitTaskResponse batchSubmitTaskResponse = salesPlanService.batchSubmitTask(batchSubmitTaskRequest);

            json = new JSONObject();
            json.put("success", batchSubmitTaskResponse.getResult().getSucNum() > 0);
            if (MapUtils.isNotEmpty(batchSubmitTaskResponse.getResult().getErrorInfoMap())) {
                Collection<String> values = batchSubmitTaskResponse.getResult().getErrorInfoMap().values();
                String collect = String.join(",", values);
                json.put("message", collect);
            }
        } catch (Exception e) {
            json.put("success", false);
            json.put("message", "页面跑丢了");
        }
        return json;
    }

    private PageQueryPlanScItemListResponse getChildOrgList(String bizId, String parentId, Integer bizType, String planId, Boolean isSales) {
        PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
        /*if (!isSales) {
            listRequest.setParentId(parentId);
        }*/
        listRequest.setPlanId(planId);
        listRequest.setBizType(bizType);
        listRequest.setBizId(bizId);
        listRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());

        PageQueryPlanScItemListResponse listResponse = null;
        listResponse = salesPlanService.pageQueryPlanScItemList(listRequest);
        if (Objects.isNull(listResponse)) {
            listResponse.setResult(new ArrayList());
            listResponse.setTotal(0);
            listResponse.setSuccess(true);
        }
        return listResponse;
    }

    @Data
    public class Biz {
        private String bizId;
        private Integer bizType;
    }
}
